package com.xx.ems.dao.impl;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.xx.ems.dao.EquipmentCRUDDao;
import com.xx.ems.model.Accessory;
import com.xx.ems.model.Equipments;
import com.xx.ems.system.BaseDao;

@Repository(value="EquipmentCRUDDao")
@Transactional
public class EquipmentCRUDDaoImpl extends BaseDao implements EquipmentCRUDDao {
	@Override
	public List<Integer> addEquipment(int enternum, Equipments equipments, List<Accessory> accessoryList) {
		List<Integer> eidarray = new ArrayList<Integer>();
		for (int i = 0; i < enternum; i++) {
			/**
			 * 生成设备的编号
			 */
			String enumber = getEquipmentBase().generateEquipmentCode(equipments.getType().getTid().toString());
			equipments.setEnumber(enumber);
			/**
			 * 保存与设备相关的附件
			 */
			for (Accessory accessory : accessoryList) {
				accessory.setEquipments(equipments);
				equipments.getAccessory().add(accessory);
			}
			/**
			 * 设置设备的审核状态
			 */
			equipments.setApprove_status(0);
			/**
			 * 保存设备信息
			 */
			int eid = (Integer) getCurrentSession().save(equipments);
			eidarray.add(eid);
		}
		return eidarray;
	}

	@Override
	public void updateEquipment(Equipments equipments, List<Accessory> accessoryList) {
		/**
		 * 根据设备的id,获取相应的设备对象
		 */
		Equipments oldEquipment = (Equipments) getCurrentSession().get(Equipments.class, equipments.getEid());
		/**
		 * 将修改的设备信息覆盖旧的设备信息
		 */
		BeanUtils.copyProperties(oldEquipment, equipments);
		/**
		 * 修改设备相应的附件
		 */
		for (Accessory accessory : accessoryList) {
			/**
			 * 判断附件是新增还是修改
			 */
			if (accessory.getAid() == null) {
				oldEquipment.getAccessory().add(accessory);
			}else {
				/**
				 * 根据附件的id,获取相应的附件对象
				 */
				Accessory oldAccessory = (Accessory) getCurrentSession().get(Accessory.class, accessory.getAid());
				/**
				 * 将修改的附件信息覆盖旧的附件信息
				 */
				BeanUtils.copyProperties(oldAccessory, accessory);
				/**
				 * 保存更新后的附件信息
				 */
				getCurrentSession().update(oldAccessory);
			}
		}
		/**
		 * 保存更新后的设备信息
		 */
		getCurrentSession().saveOrUpdate(oldEquipment);
	}

	@Override
	public void deleteEquipment(int[] eids) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void deleteAccessory(String[] aids) {
		/**
		 * 删除指定附件的hql
		 */
		String hql = "delete from Accessory ac where ac.aid = :id";
		Query query = getCurrentSession().createQuery(hql);
		/**
		 * 循环删除附件信息
		 */
		for (String aid : aids) {
			/**
			 * 设置要删除的附件的id
			 */
			query.setInteger("id", Integer.valueOf(aid));
			query.executeUpdate();
		}
	}
	
	@Override
	public void bindEimgWithEquipment(List<Integer> eidArray, String eimgPath) {
		for (Integer eid : eidArray) {
			Equipments equipment = (Equipments) getCurrentSession().get(Equipments.class, eid);
			equipment.setEquipment_img(eimgPath);
			getCurrentSession().update(equipment);
		}
	}
	
	@Override
	public void approveEquipment(List<Integer> eidArray, List<Integer> approveResult) {
		for (int i = 0; i < eidArray.size(); i++) {
			Equipments equipment = (Equipments) getCurrentSession().get(Equipments.class, eidArray.get(i));
			equipment.setApprove_status(approveResult.get(i));
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> getEquipmentList(int pageNow, int maxCount) {
		/**
		 * 获取设备列表
		 */
		String hql = "from Equipments equip order by equip.in_time desc";
		List<Equipments> equipmentList = getPagingList(pageNow, maxCount, hql);
		List<Object> list = new ArrayList<Object>();
		for (Equipments equipment : equipmentList) {
			list.add(equipment.toHashMap());
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", list);
		map.put("totalpage", getTotalpage());
		return map;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Object> getAccessoryByEquipmentId(int eid) {
		/**
		 * 获取指定设备所拥有的附件
		 */
		List<Accessory> accessoryList = (List<Accessory>) getCurrentSession().createQuery("from Accessory ac where ac.fk_eid = "+eid).list();
		List<Object> list = new ArrayList<Object>();
		for (Accessory accessory : accessoryList) {
			list.add(accessory.toHashMap());
		}
		return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> getEquipmentListByEnumberOrEname(String searchinfo, int pageNow, int maxCount) {
		String hql = "from Equipments equip where equip.enumber like '%" + searchinfo + "%' or equip.ename like '%" + searchinfo + "%'";
		List<Equipments> equipmentList = getPagingList(pageNow, maxCount, hql);
		List<Object> list = new ArrayList<Object>();
		for (Equipments equipment : equipmentList) {
			list.add(equipment.toHashMap());
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", list);
		map.put("totalpage", getTotalpage());
		return map;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> getEquipmentListByCriteriaQuery(int pageNow, int maxCount, Equipments equipment, double eprice2, Date in_time2, Date produced_date2, int deadline2, Date buy_time2) throws ParseException {
		Criteria cr = getCurrentSession().createCriteria(Equipments.class); 
		/**
		 * 设置关联类的别名
		 */
		cr.createAlias("Users", "user");
		cr.createAlias("Etypes","etypes");
		cr.createAlias("Estatus","estatus");
		cr.createAlias("Esource","esource");
		cr.createAlias("Providers","providers");
		cr.createAlias("Departments","department");
		
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		
		/**
		 * 判断设备名称
		 */
		if(equipment.getEname() != null){
			cr.add(Restrictions.like("ename", "%" + equipment.getEname() + "%"));
		}
		/**
		 * 判断设备的价格
		 */
		if(equipment.getEprice() != 0 && eprice2 != 0){
			cr.add(Restrictions.between("eprice", equipment.getEprice(), eprice2));
		}
		/**
		 * 判断负责人 
		 */
		if(equipment.getDuty().getUsername() != null){
			cr.add(Restrictions.like("user.username", "%" + equipment.getDuty().getUsername() + "%"));									
		}
		/**
		 * 判断设备的型号
		 */
		if(equipment.getEmodel() != null){
			cr.add(Restrictions.like("emodel", "%" + equipment.getEmodel() + "%"));
		}
		/**
		 * 判断设备的状态
		 */
		if(equipment.getStatus().getSname() != null){
			cr.add(Restrictions.like("estatus.sname", "%" + equipment.getStatus().getSname() + "%"));
		}
		/**
		 * 判断设备的来源
		 */
		if(equipment.getSource().getSname() != null){
			cr.add(Restrictions.like("esource.sname", "%" + equipment.getSource().getSname() + "%"));
		}
		/**
		 * 判断设备的厂家
		 */
		if(equipment.getManufacturers() != null){
			cr.add(Restrictions.like("manufacturers", "%" + equipment.getManufacturers() + "%"));
		}
		/**
		 * 判断入库时间
		 */
		if(equipment.getIn_time() != null && in_time2 != null){
		    cr.add(Restrictions.between("entrytime",df.parse(df.format(equipment.getIn_time())),df.parse(df.format(in_time2))));
		}else if(equipment.getIn_time() != null){
			cr.add(Restrictions.gt("entrytime",df.parse(df.format(equipment.getIn_time()))));
		}else if(in_time2 != null){
			cr.add(Restrictions.lt("entrytime",df.parse(df.format(in_time2))));
		}
		/**
		 * 判断出厂时间
		 */
		if(equipment.getProduced_date() != null && produced_date2 != null){
			cr.add(Restrictions.between("produced_date", df.parse(df.format(equipment.getProduced_date())), df.parse(df.format(produced_date2))));
		}else if(equipment.getProduced_date() != null){
			cr.add(Restrictions.gt("lf_time",df.parse(df.format(equipment.getProduced_date()))));
		}else if(produced_date2 != null){
			cr.add(Restrictions.lt("lf_time",df.parse(df.format(produced_date2))));
		}
		/**
		 * 判断设备年限
		 */
		if(equipment.getDeadline() != null && deadline2 != 0){
			cr.add(Restrictions.between("deadline", equipment.getDeadline(), deadline2));
		}else if(equipment.getDeadline() != null){
			cr.add(Restrictions.gt("deadline", equipment.getDeadline()));
		}else if(deadline2 != 0){
			cr.add(Restrictions.lt("deadline", deadline2));
		}
		/**
		 * 判断设备的购买时间
		 */
		if(equipment.getBuy_time() != null && buy_time2 != null){
			cr.add(Restrictions.between("buytime", df.parse(df.format(equipment.getBuy_time())), df.parse(df.format(buy_time2))));
		}else if(equipment.getBuy_time() != null){
			cr.add(Restrictions.gt("buytime",df.parse(df.format(equipment.getBuy_time()))));
		}else if(buy_time2 != null){
			cr.add(Restrictions.lt("buytime",df.parse(df.format(buy_time2))));
		}
		/**
		 * 判断设备的供应商
		 */
		if(equipment.getProvider().getPname() != null){
			cr.add(Restrictions.like("providers.pname", "%" + equipment.getProvider().getPname() + "%"));
		}
		/**
		 * 判断设备的放置点
		 */
		if(equipment.getStorage() != null){
			cr.add(Restrictions.like("storage", "%" + equipment.getStorage() + "%"));
		}
		/**
		 * 判断设备的类型
		 */
		if(equipment.getType().getTname() != null){
			cr.add(Restrictions.like("etypes.tname", "%" + equipment.getType().getTname() + "%"));
		}
		//判断设备的使用部门
		/*if(equipment.getDepartments().getDname() != null){
			cr.add(Restrictions.in("department.did", equipment.getDepartments().getDname()));
		}*/
		
		List<Equipments> list = null;
		//如果pageNOw为-1时查询全部符合条件的信息
		if(pageNow == -1) {
			list = cr.list();
		}else {
			list = getPagingListByCriteria(pageNow, maxCount, cr);
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", list);
		map.put("totalpage", getTotalpage());
		return map;
	}
}